package servlet;

import dao.BlogDao;
import entity.Blog;
import entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ZhangYufei
 * Date: 2021-07-22
 * Time: 16:06
 */
@WebServlet("/blogEdit")
public class BlogEditServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        //0. 判定用户是已经登录
        HttpSession session = req.getSession(false);
        if(session == null){
            resp.sendError(404,"当前尚未登录，不能发布博客");
            return;
        }
        User user = (User) session.getAttribute("user");
        if(user == null){
            resp.sendError(404,"当前尚未登录，不能发布博客");
            return;
        }
        //1. 读取请求中的参数
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        if(title == null || content == null || "".equals(content) || "".equals(title)){
            resp.sendError(404,"标题和输入框不能为空");
            return;
        }

        //2. 根据读取到的数据构造一个 Blog 对象，插入到数据库中
        Blog blog = new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        blog.setUserId(user.getId());
        BlogDao blogDao = new BlogDao();
        blogDao.insert(blog);

        //3. 重定向到列表页面，可以看到新插入的博客
        resp.sendRedirect("blogList");
    }
}
